package com.socialbank.web.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.wqdata.auth.bean.Menu;
import com.wqdata.auth.util.UserUtils;

@Controller
public class LoginController {
private static Logger logger = Logger.getLogger(LoginController.class);
	
	@RequestMapping("toLogin")
	public String toLogin(){
		return "login";
	}
	
	@RequestMapping("login")
	public String login(HttpServletRequest request) throws Exception {

		// 如果登陆失败从request中获取认证异常信息，shiroLoginFailure就是shiro异常类的全限定名
		String exceptionClassName = (String) request.getAttribute("shiroLoginFailure");
		// 根据shiro返回的异常类路径判断，抛出指定异常信息
		if(exceptionClassName!=null){
			if (UnknownAccountException.class.getName().equals(exceptionClassName)) {
				//最终会抛给异常处理器
				request.setAttribute("result", "账号不存在");
				logger.error("账号不存在");
				//throw new RuntimeException("账号不存在");
			} else if (IncorrectCredentialsException.class.getName().equals(
					exceptionClassName)) {
				request.setAttribute("result", "用户名/密码错误");
				logger.error("用户名/密码错误");
				//throw new RuntimeException("用户名/密码错误");
			} else {
				//throw new Exception();//最终在异常处理器生成未知错误
				logger.error(exceptionClassName+"未知错误");
				request.setAttribute("result", "未知错误");
			}
		}
		// 此方法不处理登陆成功（认证成功），shiro认证成功会自动跳转到上一个请求路径
		// 登陆失败还到login页面
		return "login";
	}
	
	@RequestMapping("/main")
	public String main(HttpSession httpSession){
		//model.addAttribute("menuList", UserUtils.getActiveUser().getMenus());
		//httpSession.setAttribute("menuList", UserUtils.getActiveUser().getMenus());
		return "activityManager/bankActivity";
	}
	
	@RequestMapping(value = "/navMenu",method = RequestMethod.GET)
	public @ResponseBody Object getNavMenu(){
		List<Menu> menuList = UserUtils.getActiveUser().getMenus();
		return menuList;
	}
}
